const bcrypt = require('bcryptjs');

module.exports = function ({Auths}) {

    /**
     * 验证密码 V2
     */
    Auths.validateV2 = function ({user_id, password}) {
        return Auths.findOne({
            where: {user_id: user_id, type: 'Login'},
            attributes: ['id', 'password']
        }).then(function (auth) {
            if (!auth) return {success: false, message: '用户没有设置密码'};

            if (bcrypt.compareSync(password, auth.password)) {
                return {success: true};
            }
            return {success: false, message: '密码错误'};
        });
    }

    /**
     * 创建密码 V2
     */
    Auths.addV2 = function ({auth, t}) {
        auth.password = bcrypt.hashSync(auth.password, 8);
        return Auths.create(auth, {transaction: t});
    }

    /**
     * 忘记密码或设置密码 V2
     * 判断密码是否存在,没有就创建,有就更新
     */
    Auths.forgotV2 = function ({user_id, password}) {
        return Auths.findOne({where: {user_id: user_id, type: 'Login'}, attributes: ['id', 'password']}).then(function (auth) {
            if (auth) {
                return Auths.update({password: bcrypt.hashSync(password, 8)}, {where: {id: auth.id}}).then(function (result) {
                    return {success: (result[0] > 0)};
                });
            } else {
                return Auths.create({
                    password: bcrypt.hashSync(password, 8),
                    user_id: user_id
                }).then(function () {
                    return {success: true};
                });
            }
        });
    }

    /**
     * 修改密码 V2
     */
    Auths.changeV2 = function ({user_id, oldpassword, newpassword}) {
        return Auths.findOne({where: {user_id: user_id, type: 'Login'}, attributes: ['id', 'password']}).then(function (auth) {
            if (!auth) {
                return {success: false, message: '用户没有设置密码, 请通过忘记密码重置'};
            }
            if (oldpassword && !bcrypt.compareSync(oldpassword, auth.password)) {
                return {success: false, message: '旧密码错误'};
            }
            return Auths.update({password: bcrypt.hashSync(newpassword, 8)}, {where: {id: auth.id}}).then(function (result) {
                return {success: (result[0] > 0)};
            });
        });
    }
}